package com.kusej.gitmanger.form;

import com.intellij.icons.AllIcons;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.kusej.gitmanger.utils.GitBranchUtils;
import lombok.Data;
import org.eclipse.jgit.api.FetchCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.transport.*;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URISyntaxException;

@Data
public class MyGitSetting {
    private JPanel contentPanel;
    private JTextField username;
    private JTextField password;
    private JTextField originUrl;
    private JLabel warning;
    private JButton loginButton;
    private Project project;

    public MyGitSetting(Project project) {
        this.project = project;
        loginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                try {
                    String username = MyGitSetting.this.username.getText();
                    String password = MyGitSetting.this.password.getText();
                    String remoteUrl = MyGitSetting.this.originUrl.getText();
                    // 设置远程仓库的URL和用户名密码
                    URIish remoteUri = new URIish(remoteUrl);
                    CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider(username, password);
                    // 创建一个FetchCommand对象
                    Repository repository = GitBranchUtils.openRepository(project.getBasePath());
                    FetchCommand fetchCommand = Git.wrap(repository).fetch().setRefSpecs(new RefSpec("+refs/heads/*:refs/remotes/origin/*"));
                    fetchCommand.setRemote(remoteUri.toString());
                    fetchCommand.setCredentialsProvider(credentialsProvider);
                    // 执行fetch命令来验证用户名和密码是否正确
                    fetchCommand.call();
                    Messages.showMessageDialog("Success,连接成功", "Message", AllIcons.Actions.Commit);
                } catch (Exception e) {
                    e.printStackTrace();
                    Messages.showErrorDialog("连接失败：" + e.getMessage(), "ERROR");
                }
            }
        });
    }
}
